﻿
using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.UI;
using WSS.BLL.Account;
using WSS.Pub;

namespace WSS.Web.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/

        public ActionResult Login()
        {
            var list = DB.ListSod("LIST2_HOSP_HOSPITAL", null);

            ViewBag.SELECT_HOSPTIAL = list.ToSelectListItem("HOSP_ID", "HOSP_NAME");
            return View();
        }

        /// <summary>
        /// 未通过 MyAuthorize 认证，跳转到此
        /// </summary>
        /// <returns></returns>
        public ActionResult NotCertified()
        {
            string fromurl = Request.Req("ReturnUrl");
            if (string.IsNullOrEmpty(fromurl))
            {
                fromurl = "/login/login";
            }

            ViewBag.FROMURL = fromurl;
            return View();
        }

        /// <summary>
        /// 登录操作
        /// </summary>
        /// <param name="u">user no</param>
        /// <param name="p">password</param>
        /// <param name="v">verifycode</param>
        /// <param name="h">hospital</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DoLogin(string u, string p, string v, string h)
        {
            var flag = false;
            var message = "";
            if (!string.IsNullOrEmpty(u) && !string.IsNullOrEmpty(p))
            {
                //使用验证码
                var lh = new LoginHelper();
                flag = lh.Login(ref message, u, p, v, h);
            }

            if (!flag)
            {
                return this.MyJson(false, message);
            }


            //http://hi.baidu.com/aidfan/item/a4a9040fbf77bdce90571834
            //http://www.cnblogs.com/klete/archive/2004/12/13/76518.html


            string userdata = message;

            FormsAuthenticationTicket ticket =
                new FormsAuthenticationTicket(1,                          // 版本
                                              "IWellAuth",                // 用户名
                                              DateTime.Now,               // 创建
                                              DateTime.Now.AddHours(8),// 到期
                                              false,                      // 永久
                                              userdata);
            //加密验证票
            string encryted_ticket = FormsAuthentication.Encrypt(ticket);

            //生成Cookie对象．
            //FormsAuthentication.FormsCookieName取得WebConfig中<Authentication>
            //配置节中Name的值作为Cookie的名字．
            HttpCookie auth_cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryted_ticket);
            Response.Cookies.Add(auth_cookie);

            //Response.Redirect(FormsAuthentication.GetRedirectUrl("IWellAuth", false));
            return this.MyJson(true, "");
        }

        /// <summary>
        /// 前端锁定，后端登出，以防刷新页面，跳过锁屏
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public ActionResult AutoLock(string userid)
        {
            return _Lock(userid, 1);
        }

        public ActionResult HandLock(string userid)
        {
            return _Lock(userid, 0);
        }

        /// <summary>
        /// 前端锁定，后端登出，以防刷新页面，跳过锁屏
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="auto">手动=0，自动1</param>
        /// <returns></returns>
        private ActionResult _Lock(string userid, int auto)
        {
            var model = UserOnline.GetOnlineUserByUserId(userid);
            if (model == null || model.UserId == null)
            {
                return this.MyJson(true, "timeout");
            }
            var actiontime = model.ActionTime;
            if (auto == 0)
            {
                actiontime = DateTime.Now.AddHours(-8);
            }
            var now = DateTime.Now;
            var ts = now.Subtract(actiontime);
            if (ts.TotalMinutes >= 10)
            {
                UserOnline.RemoveOnlineUser(model.Guid);
                return this.MyJson(true, "lock");
            }
            return this.MyJson(false, "ok");
        }

        /// <summary>
        /// 屏幕解锁
        /// </summary>
        /// <param name="userpwd"></param>
        /// <returns></returns>
        public ActionResult UnLockScreen(string userpwd)
        {
            var httpContext = System.Web.HttpContext.Current;

            if (httpContext == null)
            {
                return this.MyJson(false, "浏览器异常");
            }

            if (!httpContext.User.Identity.IsAuthenticated)
            {
                return this.MyJson(false, "客户端用户验证失败");
            }

            string userdata = ((System.Web.Security.FormsIdentity)(httpContext.User.Identity)).Ticket.UserData;

            if (string.IsNullOrEmpty(userdata))
            {
                return this.MyJson(false, "登录凭据丢失，请重新登录吧");
            }

            string[] arr_userdata = userdata.Split(',');

            if (arr_userdata.Length != 4)
            {
                return this.MyJson(false, "登录凭据被人为修改，请重新登录");
            }

            string guid = arr_userdata[0];
            string userid = arr_userdata[1];
            string userno = arr_userdata[2];
            string hospitalid = arr_userdata[3];

            string message = "";
            var lh = new LoginHelper();
            var flag = lh.UnLockScreen(ref message, userid, userpwd, hospitalid, guid);
            message = flag ? "" : message;

            return this.MyJson(flag, message);
        }

    }
}
